package com.objecteffects.template.persist.jpa;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;

import com.google.inject.Inject;
import com.google.inject.Provider;

import com.objecteffects.template.model.BlogPostsOffsetEntity;
import com.objecteffects.template.persist.api.IBlogPostsOffsetEntityDao;
import com.objecteffects.template.util.logger.InjectLogger;

import org.slf4j.Logger;

public class BlogPostsOffsetEntityDao extends
    AbstractJpaDao<BlogPostsOffsetEntity> implements IBlogPostsOffsetEntityDao {
    @InjectLogger
    private Logger log;

    @Inject
    BlogPostsOffsetEntityDao(
        final Provider<EntityManager> _entityManagerProvider) {
        super(_entityManagerProvider);
    }

    @Override
    public BlogPostsOffsetEntity findByUserIdAndUrl(final Long userId,
        final String url) {

        final TypedQuery<BlogPostsOffsetEntity> query =
            this.getEntityManager()
                .createNamedQuery("BlogPostsOffsetEntity.findByUserIdAndUrl",
                                  BlogPostsOffsetEntity.class);

        query.setParameter("id", userId);
        query.setParameter("url", url);

        final List<BlogPostsOffsetEntity> result = query.getResultList();

        this.log.debug("userId: {}, result: {}", userId, result);

        if (result.isEmpty()) {
            return null;
        }

        if (result.size() > 1) {
            this.log.warn("multiple entities for userId: {}", userId);
        }

        return result.get(0);
    }
}
